package com.easymin.weixin.service.impl;

import com.easymin.weixin.entity.WxAccount;
import com.easymin.weixin.entity.WxAccountCriteria;
import com.easymin.weixin.entity.WxAccountCriteria.Criteria;
import com.easymin.weixin.mapper.BaseMapper;
import com.easymin.weixin.mapper.WxAccountMapper;
import com.easymin.weixin.service.WxAccountService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by shine on 15/8/19.
 */
@Service
public class DefaultWxAccountService extends AbstractBaseService<WxAccount, WxAccountCriteria, Long> implements WxAccountService {

  @Autowired
  private WxAccountMapper wxAccountMapper;

  @Override
  public BaseMapper<WxAccount, WxAccountCriteria, Long> getMapper() {

    return wxAccountMapper;
  }

  @Override
  public int insert(WxAccount wxAccount) {

    wxAccount.setCreated(new Date());
    wxAccount.setUpdated(new Date());
    wxAccount.setVersion(1);
    return super.insert(wxAccount);
  }

  @Override
  public WxAccount exists(String name) {

    WxAccountCriteria criteria = new WxAccountCriteria();
    criteria.createCriteria().andNameEqualTo(name);
    List<WxAccount> list = wxAccountMapper.selectByExample(criteria);
    return list.size() != 0 ? list.get(0) : null;
  }

  @Override
  public int update(WxAccount wxAccount) {

    wxAccount.setUpdated(new Date());
    return super.update(wxAccount);
  }

  @Override
  public WxAccount findBy(String appid, Long wxApplicationId) {

    WxAccountCriteria wxAccountCriteria = new WxAccountCriteria();
    wxAccountCriteria.createCriteria()
            .andWxappIdEqualTo(appid)
            .andApplicationIdEqualTo(wxApplicationId);

    List<WxAccount> wxAccounts = wxAccountMapper.selectByExample(wxAccountCriteria);

    if (!CollectionUtils.isEmpty(wxAccounts)) {
      return wxAccounts.get(0);
    }


    return null;
  }

  @Override
  public WxAccount findByFileName(String fileName) {
    
    return wxAccountMapper.findByFileName(fileName);
  }
}
